from app01 import models
from stark.service import stark
from stark.service.stark import StarkHandler


class ConsultRecordConfig(StarkHandler):
    list_display = ['customer', 'consultant', 'note', 'date']

    def get_queryset(self, request, *args, **kwargs):
        cid = request.GET.get('cid')
        if not cid:
            return self.model_class.objects
        return self.model_class.objects.filter(customer_id=cid)


class PrivateConsultRecordModelForm(stark.StarkModelForm):
    class Meta:
        model = models.ConsultRecord
        exclude = ['customer', 'consultant']


class PrivateModelForm(stark.StarkModelForm):
    class Meta:
        model = models.ConsultRecord
        exclude = ['consultant']


class PrivateConsultRecordConfig(ConsultRecordConfig):
    def get_model_form_class(self, is_add, request, pk, *args, **kwargs):
        if request.GET.get('_filter'):
            return PrivateConsultRecordModelForm
        else:
            return PrivateModelForm

    def get_queryset(self, request, *args, **kwargs):
        cid = request.GET.get('cid')
        user_id = request.session.get('user_info')['id']
        query = self.model_class.objects.filter(customer__consultant_id=user_id)
        if not cid:
            return query
        return query.filter(customer_id=cid)

    def save(self, request, form, is_update, *args, **kwargs):
        user_id = request.session.get('user_info')['id']
        form.instance.consultant = models.UserInfo.objects.filter(id=user_id).first()
        if request.GET.get('_filter'):
            cid, id = request.GET.get('_filter').split('=')
            form.instance.customer = models.Customer.objects.filter(id=id).first()
        form.save()


